from datetime import datetime

from django.contrib import admin
from django.contrib.auth.models import User
from django.utils import timezone
from import_export.admin import ImportExportModelAdmin

from . import models
from .resources import UserExtractionResource


def get_today_full_info():
    now = datetime.now()

    # 日期格式
    date_str = now.strftime("%Y年%m月%d日")

    # 星期中文
    weekdays = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
    weekday_str = weekdays[now.weekday()]

    # ISO 周数（国际标准，推荐）
    week_num = now.strftime("%V")  # 返回字符串，如 "14"

    return f"{date_str} {weekday_str} (第{week_num}周)"


admin.site.site_title = "西蒙来了"

admin.site.site_header = "西蒙来了管理系统"
admin.site.index_title = f"欢迎 🐙 今天是 {get_today_full_info()}"
admin.site.site_url = 'https://www.dedao.cn/bought'
# Register your models here.


class FormBaseConfig(ImportExportModelAdmin):
    """
    通用 Admin 基类，适用于所有继承 BaseModel 的模型
    自动处理：
    - create_at / update_at（时间）
    - created_by / updated_by（用户）
    """

    def save_model(self, request, obj, form, change):
        # 确保 request.user 是 User 实例
        if not isinstance(request.user, User):
            super().save_model(request, obj, form, change)
            return

        # 获取当前时间
        now = timezone.now()

        if not change:  # 新建对象
            if obj.created_at is None:
                obj.created_at = now
            if obj.updated_at is None:
                obj.updated_at = now
            if obj.created_by is None:
                obj.created_by = request.user
            obj.updated_by = request.user
        else:  # 更新对象
            obj.update_at = now  # 手动更新 update_at
            obj.updated_by = request.user  # 更新人

        # 调用父类保存方法
        super().save_model(request, obj, form, change)

    # 可选：在 Admin 表单中显示这些字段为只读
    readonly_fields = ['created_at', 'updated_at', 'created_by', 'updated_by']
    # fields = ['field1', 'field2', 'field3']  # 只显示这些字段
    exclude = ['id',]  # 隐藏这些字段

    # fieldsets = [
    #     ('基本信息', {
    #         'fields': ['field1', 'field2']
    #     }),
    #     ('高级设置', {
    #         'fields': ['field3', 'field4'],
    #         'classes': ['collapse']  # 可选：折叠该字段集
    #     }),
    # ]


@admin.register(models.UserExtraction)
class AppAdmin(FormBaseConfig):
    resource_class = UserExtractionResource
    list_display = ('id', 'user_id', 'avator', 'phone_number',
                    'created_at', 'updated_at', 'active')
    search_fields = ('user_id', 'phone_number')
    list_filter = ('created_at', 'updated_at')


@admin.register(models.Menu)
class MenuAdmin(FormBaseConfig):
    list_display = ('id', 'name', 'path', 'icon', 'order',
                    'tag', 'created_at', 'updated_at', 'active')
    search_fields = ('name', 'path', 'tag')
    list_filter = ('created_at', 'updated_at', 'active')
